package com.jhd.fuzhou.view.random;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.adapter.PhotoAdapter;
import com.jhd.fuzhou.util.ShowBottomDialog;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DoubleRandomService;
import com.jhd.fuzhou.service.PDFService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.SaveSupervisionInspection;
import com.jhd.fuzhou.util.StartProcess;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.DetectedItemsVo;
import com.jhd.fuzhou.vo.DocTemplateVo;
import com.jhd.fuzhou.vo.IllegalRecordDtlVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisionInspectionPhotoVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.StartProcess.start;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;


public class DoubleStepFourActivity extends BaseActivity {

    private List<DetectedItemsVo> detectedItemsVoList = new ArrayList<>();//所有的检测
    private List<DetectedItemsVo> detectedItemsVoList1 = new ArrayList<>();//快速检测
    private List<DetectedItemsVo> detectedItemsVoList2 = new ArrayList<>();//实验室检测
    @BindView(R.id.tv_num_supervision_inspection)
    TextView tv_num_supervision_inspection;//监督检测的数量
    @BindView(R.id.tv_num_check)
    TextView tv_num_check;//监督抽测的数量
    @BindView(R.id.tv_num_quick_check)
    TextView tv_num_quick_check;//快速检测的数量
    @BindView(R.id.tv_num_laboratory_check)
    TextView tv_num_laboratory_check;//实验室检测数量
    @BindView(R.id.tv_num_illegalBehavior)
    TextView tv_num_illegalBehavior;//违法数量
    @BindView(R.id.tv_add_illegal)
    TextView tv_add_illegal;//添加违法行为
    //@BindView(R.id.tv_add_record)TextView tv_add_record;//添加添加笔录
    @BindView(R.id.rel_scene_record)
    RelativeLayout rel_scene_record;//跳转现场笔录
    @BindView(R.id.rel_health_supervision)
    RelativeLayout rel_health_supervision;//跳转卫生监督意见书
    @BindView(R.id.rel_asking_record)
    RelativeLayout rel_asking_record;//跳转询问笔录
    @BindView(R.id.tv_scene_record)
    TextView tv_scene_record;//跳转询问笔录
    @BindView(R.id.tv_health_supervision)
    TextView tv_health_supervision;//
    @BindView(R.id.tv_asking_record_status)
    TextView tv_asking_record_status;//
    @BindView(R.id.rv_illegal)
    RecyclerView rv_illegal;//
    @BindView(R.id.btn_back)
    Button btn_back;//上一步
    @BindView(R.id.btn_upload)
    Button btn_upload;//上传
    @BindView(R.id.lin_double_random)
    LinearLayout lin_double_random;
    @BindView(R.id.rv_image)RecyclerView rv_image;//上传图片的RecyclerView
    private Context context = this;
    private List<DocTemplateVo> docTemplateVoList = null;
    private List<SuperviseEnclosureVo> superviseEnclosureVoList = new ArrayList<>();
    private List<SupervisionInspectionPhotoVo> supervisionInspectionPhotoVoList;
    private PhotoAdapter photoAdapter;
    private String photoTemplateUrl;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_step_four);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        lin_double_random.setVisibility(View.VISIBLE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        LinearLayoutManager imageLayoutManager = new LinearLayoutManager(context);
        rv_illegal.setLayoutManager(linearLayoutManager);rv_image.setLayoutManager(imageLayoutManager);
        if(supervisionInspectionVo.getSuperviseEnclosureVoList()!=null){
            setEnclosureVo();
        }else{
            supervisionInspectionVo.setSuperviseEnclosureVoList(superviseEnclosureVoList);
        }
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        supervisionInspectionPhotoVoList=supervisionInspectionVo.getSupervisionInspectionPhotoVoList();
        if(supervisionInspectionPhotoVoList!=null){
            photoAdapter =new PhotoAdapter(context,supervisionInspectionVo,supervisionInspectionPhotoVoList,"双随机",photoTemplateUrl);
        }else{
            supervisionInspectionPhotoVoList=new ArrayList<>();
            photoAdapter =new PhotoAdapter(context,supervisionInspectionVo,supervisionInspectionPhotoVoList,"双随机",photoTemplateUrl);
        }
        rv_image.setAdapter(photoAdapter);
        if("1".equals(supervisionInspectionVo.getIsOnlyLook())){
            btn_upload.setText("关闭");
        }
        showDetectedItems();
        getDocTemplateList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        supervisionInspectionPhotoVoList=supervisionInspectionVo.getSupervisionInspectionPhotoVoList();
        if(supervisionInspectionPhotoVoList!=null) {
            if (supervisionInspectionPhotoVoList.size() > 1) {
                photoAdapter.notifyDataSetChanged();
            } else if (supervisionInspectionPhotoVoList.size() == 1) {
                photoAdapter = new PhotoAdapter(context, supervisionInspectionVo, supervisionInspectionPhotoVoList, "双随机", photoTemplateUrl);
                rv_image.setAdapter(photoAdapter);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        showDetectedItems();
    }
    /*显示检测等的数量*/
    public void showDetectedItems() {
        if (supervisionInspectionVo.getDetectedItemsVoList() != null) {
            detectedItemsVoList = supervisionInspectionVo.getDetectedItemsVoList();
            int quickNumber = 0;
            int laboratoryNumber = 0;
            for (DetectedItemsVo detectedItemsVo : detectedItemsVoList) {
                if (detectedItemsVo.getCheckType().equals("0")) {
                    detectedItemsVo.setSort(++quickNumber);
                    detectedItemsVoList1.add(detectedItemsVo);
                } else if (detectedItemsVo.getCheckType().equals("1")) {
                    detectedItemsVo.setSort(++laboratoryNumber);
                    detectedItemsVoList2.add(detectedItemsVo);
                }
            }
            tv_num_quick_check.setText(String.valueOf(detectedItemsVoList1.size()));
            tv_num_laboratory_check.setText(String.valueOf(detectedItemsVoList2.size()));
        }
        if(supervisionInspectionVo.getDoubleRandomInspectionContentList()!=null){
            tv_num_check.setText(String.valueOf(supervisionInspectionVo.getDoubleRandomInspectionContentList().size()));
        }
        tv_num_supervision_inspection.setText(String.valueOf(supervisionInspectionVo.getSupervisionInspectionContentList().size()));
        if (supervisionInspectionVo.getIllegalRecordDtlVoList() != null) {
            rv_illegal.setVisibility(View.VISIBLE);
            tv_num_illegalBehavior.setText(String.valueOf(supervisionInspectionVo.getIllegalRecordDtlVoList().size()));
            IllegalAdapter adapter = new IllegalAdapter(supervisionInspectionVo.getIllegalRecordDtlVoList());
            rv_illegal.setAdapter(adapter);
        } else {
            rv_illegal.setVisibility(View.GONE);
        }
        setEnclosureVo();
    }
    private void setEnclosureVo(){
        List<SuperviseEnclosureVo> superviseEnclosureVoList = supervisionInspectionVo.getSuperviseEnclosureVoList();
        for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
            if (superviseEnclosureVo.getEnclosureName().equals("现场笔录")) {
                tv_scene_record.setText("已制作");
                tv_scene_record.setTextColor(getResources().getColor(R.color.black));
            } else if (superviseEnclosureVo.getEnclosureName().equals("监督意见书")) {
                tv_health_supervision.setText("已制作");
                tv_health_supervision.setTextColor(getResources().getColor(R.color.black));
            } else if (superviseEnclosureVo.getEnclosureName().equals("询问笔录")) {
                tv_asking_record_status.setText("已制作");
                tv_asking_record_status.setTextColor(getResources().getColor(R.color.black));
            }
        }
    }

    @OnClick({R.id.tv_add_illegal, R.id.rel_scene_record, R.id.rel_health_supervision, R.id.rel_asking_record, R.id.btn_back, R.id.btn_upload,R.id.tv_add_image})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_illegal://跳转到选择违法的界面
                startActivity(new Intent(context, DoubleCheckContentActivity.class));
                break;
            /*case R.id.tv_add_record://

                break;*/
            case R.id.rel_scene_record:
                if (docTemplateVoList != null) {
                    goDocument("现场笔录");
                    /*if (tv_scene_record.getText().toString().equals("未制作")) {
                    } else {
                        alertMsg("现场笔录", "你已添加过现场笔录,确认重新添加吗?");
                    }*/
                }
                break;
            case R.id.rel_health_supervision:
                if (docTemplateVoList != null) {
                    goDocument("监督意见书");
                    /*if (tv_health_supervision.getText().toString().equals("未制作")) {
                        goDocument("监督意见书");
                    } else {
                        alertMsg("监督意见书", "你已添加过监督意见书,确认重新添加吗?");
                    }*/
                }
                break;
            case R.id.rel_asking_record:
                if (docTemplateVoList != null) {
                    goDocument("询问笔录");
                    /*if (tv_asking_record_status.getText().toString().equals("未制作")) {
                        goDocument("询问笔录");
                    } else {
                        alertMsg("询问笔录", "你已添加过询问笔录,确认重新添加吗?");
                    }*/
                }
                break;
            case R.id.btn_back://上一步
                onBackPressed();
                break;
            case R.id.btn_upload:
                btn_upload.setClickable(false);
                upload();
                break;
            case R.id.tv_add_image:
                ShowBottomDialog.showBottomDialog(context,"双随机",photoTemplateUrl);
                break;
        }
    }

    /*上传表单*/
    public void upload() {
        if("关闭".equals(btn_upload.getText().toString())){
            application.exitStep();
        }else {
            Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://192.168.1.94:9004/");//URL的头
            DoubleRandomService vs = retrofit.create(DoubleRandomService.class);
            Call<JsonForResult> jsonForResultCall = vs.saveDoubleRandomManagement(application.getAccessToken(), SaveSupervisionInspection.saveDouble(supervisionInspectionVo, application));
            jsonForResultCall.enqueue(new Callback<JsonForResult>() {
                @Override
                public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                    try {
                        JsonForResult jsonForResult = response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            takeDocumentNo(supervisionInspectionVo,btn_upload,context);
                            if (StringUtil.isNullOrEmpty(supervisionInspectionVo.getId())) {
                                start(application, jsonForResult.getData().toString(), "双随机", context);
                                btn_upload.setClickable(false);
                            } else {
                                StartProcess.alertMsg2(application, supervisionInspectionVo.getTaskId(), supervisionInspectionVo.getId(), "未审核", "添加双随机成功!", context);//
                                btn_upload.setClickable(false);
                            }
                        } else {
                            btn_upload.setClickable(true);
                            CustomToast.showText(context, "添加双随机失败！", 3000, 0, 0).show();
                        }
                    } catch (Exception e) {
                        btn_upload.setClickable(true);
                        UtilHelper.alertMsg(context, "错误", e.getMessage());
                    }
                }

                @Override
                public void onFailure(Call<JsonForResult> call, Throwable t) {
                    String msg = "上传失败!";
                    btn_upload.setClickable(true);
                    UtilHelper.alertMsg(context, "错误", msg);
                }
            });
        }
    }

    /*获取文书模板*/
    public void getDocTemplateList() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("docType","日常监督文书").addParam("deptName",application.getDeptName()).addParam("supervisedUnitId",supervisionInspectionVo.getSupervisedUnitId());
        Call<JsonForResult> jsonForResultCall = vs.getDocTemplateList(application.getAccessToken(), params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    //请求授权信息
                    docTemplateVoList = JSON.parseArray(jsonForResult.getData().toString(), DocTemplateVo.class);
                    for (DocTemplateVo docTemplateVo : docTemplateVoList) {
                        if(docTemplateVo.getName().equals("现场照片证据")){
                            photoTemplateUrl=docTemplateVo.getFileUrl();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                String msg = "获取文书模板失败!";
                System.out.println(t.getStackTrace());
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    private void goDocument(String title) {
        DocTemplateVo docTemplateVo=isFind(title);
        if(docTemplateVo==null){
            CustomToast.showText(context,"未找到"+title+"模板!",3000,0,0).show();
        }else{
            if (title.equals("现场笔录")) {
                Intent intent = new Intent(context, DoubleSceneRecordActivity.class);
                intent.putExtra("fileUrl", docTemplateVo.getFileUrl());
                startActivity(intent);
            } else if (title.equals("监督意见书")) {
                Intent intent = new Intent(context, DoubleHealthSupervisionActivity.class);
                intent.putExtra("fileUrl", docTemplateVo.getFileUrl());
                startActivity(intent);
            } else if (title.equals("询问笔录")) {
                Intent intent = new Intent(context, DoubleAskingRecordActivity.class);
                intent.putExtra("fileUrl", docTemplateVo.getFileUrl());
                startActivity(intent);
            }
        }
    }
    public DocTemplateVo isFind(String title){
        for (DocTemplateVo docTemplateVo : docTemplateVoList) {
            if (docTemplateVo.getName().equals(title)) {
                return docTemplateVo;
            }
        }
        return null;
    }

    public void alertMsg(String title, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setIcon(R.mipmap.dialog_alert);
        builder.setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goDocument(title);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog dialog = builder.create();
        if (!((Activity) context).isFinishing()) dialog.show();

        int color = context.getResources().getColor(R.color.colorCyan300);
        Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        if (btn != null) btn.setTextColor(color);
    }

    public class IllegalAdapter extends RecyclerView.Adapter<IllegalAdapter.ViewHolder> {
        List<IllegalRecordDtlVo> illegalRecordDtlVoVoList;

        public IllegalAdapter(List<IllegalRecordDtlVo> illegalRecordDtlVoVoList) {
            this.illegalRecordDtlVoVoList = illegalRecordDtlVoVoList;
        }

        @NonNull
        @Override
        public IllegalAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_illegal, parent, false);
            IllegalAdapter.ViewHolder viewHolder = new IllegalAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull IllegalAdapter.ViewHolder holder, int position) {
            holder.btn_question.setText(illegalRecordDtlVoVoList.get(position).getContent());
        }

        @Override
        public int getItemCount() {
            return illegalRecordDtlVoVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView btn_question;

            public ViewHolder(View itemView) {
                super(itemView);
                this.btn_question = itemView.findViewById(R.id.btn_question);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}